#define _CRT_SECURE_NO_WARNINGS 1
#include"Tree.h"

void HeapInit(HP* ph)
{
	assert(ph);
	ph->a = NULL;
	ph->size = ph->capacity = 0;
}
void HeapDestroy(HP* ph)
{
	assert(ph);
	free(ph->a);
	ph->a = NULL;
	ph->size = ph->capacity = 0;
}
void Swap(HPDateType* p1, HPDateType* p2)
{
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}
void AdjustUp(HPDateType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[parent] > a[child])
		{
			Swap(&a[parent], &a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HeapPush(HP* ph, HPDateType x)
{
	assert(ph);
	if (ph->size == ph->capacity)
	{
		int newcapacity = ph->capacity == 0 ? 4 : ph->capacity * 2;
		HPDateType* newa = (HPDateType*)realloc(ph->a, sizeof(HPDateType) * newcapacity);
		if (newa == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ph->a = newa;
		ph->capacity = newcapacity;
	}
	ph->a[ph->size] = x;
	ph->size++;
	AdjustUp(ph->a, ph->size-1);
}
void AdjustDown(HPDateType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}
void HeapPop(HP* ph)
{
	assert(ph);
	assert(ph->size > 0);
	Swap(&ph->a[0], &ph->a[ph->size - 1]);
	--ph->size;

	AdjustDown(ph->a, ph->size, 0);
}
bool HeapEmpty(HP* ph)
{
	assert(ph);
	return ph->size == 0;
}
HPDateType HeapTop(HP* ph)
{
	assert(ph);
	assert(ph->size > 0);

	return ph->a[0];
}
void HeapPrint(HP* ph)
{
	assert(ph);
	for (int i = 0; i < ph->size; i++)
	{
		printf("%d ", ph->a[i]);
	}
	printf("\n");
}